<template>
  <div>
    <el-dialog
      v-model="visible"
      title="新建消息"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="closeDialog"
      width="618"
    >
      <el-form ref="formRef" :rules="formRules" :model="formData.form" style="margin-left: 14px">
        <el-form-item required label="推送渠道：" prop="sendType" label-width="100px">
          <el-radio-group required v-model="formData.form.sendType" @change="handleSendType">
            <el-radio v-for="item in sendList" :key="item.value" :label="item.value">
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          required
          label="标题："
          prop="title"
          style="max-width: 730px"
          label-width="100px"
        >
          <el-input v-model="formData.form.title" />
        </el-form-item>
        <el-form-item required label="消息类型：" prop="type" label-width="100px">
          <el-select
            filterable
            v-model="formData.form.type"
            placeholder=""
            placement="bottom"
            style="max-width: 730px"
          >
            <el-option v-for="item in typeList" :key="item.value" :value="item.label" />
          </el-select>
        </el-form-item>

        <div v-if="formData.form.sendType == 1">
          <el-form-item required label="选择模板：" prop="templateCode" label-width="100px">
            <el-select
              filterable
              v-model="formData.form.templateCode"
              placeholder=""
              placement="bottom"
              style="max-width: 730px"
              @change="handleTemplate"
            >
              <el-option
                v-for="item in smsList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-input :rows="5" disabled type="textarea" v-model="formData.form.content" />
            <div class="mb-20px">
              注:短信格式:【消息类型】消息标题消息标消息标题，消息内容消息内容消息内容消息内容消息内容消息内容消息内容消息内容消息内容消息内容消息
            </div>
          </el-form-item>
        </div>
        <div v-if="formData.form.sendType == 2">
          <el-form-item
            required
            label="消息内容："
            prop="content"
            style="max-width: 730px"
            label-width="100px"
          >
            <el-input type="textarea" v-model="formData.form.content" />
          </el-form-item>
        </div>
        <el-form-item label="推送方式：" prop="pushMethod" label-width="100px">
          <el-radio-group required v-model="formData.form.pushMethod" @change="handleRadio">
            <el-radio label="1">分组推送</el-radio>
            <el-radio label="2">单人推送</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item required label="接收对象：" prop="userId" label-width="100px">
          <el-select
            filterable
            v-model="formData.form.userId"
            placeholder=""
            placement="bottom"
            style="max-width: 730px"
            @change="handleUserId"
          >
            <el-option
              v-for="item in filteredOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            @click="closeDialog"
            class="btnhover"
            style="
              width: 80px;
              height: 30px;
              background-color: rgba(255, 255, 255, 1);
              border: 1px solid rgba(187, 187, 187, 1);
              color: rgba(142, 142, 142, 1);
            "
            >取消</el-button
          >
          <el-button
            @click="besurebtn"
            class="btnhover"
            style="
              width: 80px;
              height: 30px;
              background-color: #ff9900;
              border: 1px solid #ff9900;
              color: rgba(255, 255, 255, 1);
            "
          >
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import * as getMessageApi from '@/api/messageCenter/index'
import globalApi from '@/api/spb/global'
const message = useMessage()
let treeData = ref([])
const editId = ref()
const groupList = ref()
const peopleList = ref([])
const residentTags = ref([])
const typeList = ref([])
const radioId = ref('1')
const smsList = ref([])
const showSend = ref(true)
const sendList = ref([])
const groupValue = ref('')
const userIds = ref([])
const formData = reactive({
  form: {
    title: '',
    type: '',
    sendType: '2',
    userId: '',
    content: '',
    pushMethod: '1',
    templateCode: ''
  }
})
const formRules = reactive({
  title: [{ required: true, message: '标题不能为空！', trigger: 'blur' }],
  type: [{ required: true, message: '消息类型不能为空！', trigger: 'change' }],
  sendType: [{ required: true, message: '推送渠道不能为空！', trigger: 'blur' }],
  pushMethod: [{ required: true, message: '推送方式不能为空！', trigger: 'blur' }],
  userId: [{ required: true, message: '接收对象不能为空！', trigger: 'change' }],
  content: [{ required: true, message: '消息内容不能为空！', trigger: 'blur' }],
  templateCode: [{ required: true, message: '选择模板不能为空！', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref
const props = defineProps({
  visible: Boolean,
  editData: {
    type: Object
  }
})
const editVal = ref()
const emit = defineEmits(['update:visible', 'getAdd'])
const visible = computed({
  get: () => {
    return props.visible
  },
  set: (val) => {
    emit('update:visible', val)
  }
})
watch(
  () => props.editData,
  (val) => {},
  { immediate: true }
)
const handleTemplate = (val) => {
  const selectedTemplate = smsList.value.find((template) => template.value === val)
  if (selectedTemplate) {
    formData.form.content = selectedTemplate.content
  }
}

/** 取消 */
const closeDialog = () => {
  visible.value = false
  emit('getAdd', props.editData.pageNo)
  formRef.value.resetFields()
}

/** 获取分组推送 */
const getGroupPush = () => {
  const params = {
    pageNo: 1,
    pageSize: 100,
    dictType: 'countryside_resident_label'
  }
  globalApi.getDictData(params).then((res) => {
    groupList.value = res.list
  })
}
/** 渠道 */
const getSendType = () => {
  const params = {
    pageNo: 1,
    pageSize: 100,
    dictType: 'countryside_message_send_type'
  }
  globalApi.getDictData(params).then((res) => {
    sendList.value = res.list.map((item) => ({
      label: item.label === 'miniapp' ? '小程序' : '短信',
      value: item.value
    }))
  })
}
/** 获取短信编码 */
const getSmsList = () => {
  const params = {
    pageNo: 1,
    pageSize: 100
  }
  getMessageApi.getSmsPage(params).then((res) => {
    smsList.value = res.list.map((item) => ({
      label: item.name,
      value: String(item.code),
      content: item.content
    }))
  })
}
/** 获取消息类型 */
const getmessageType = () => {
  const params = {
    pageNo: 1,
    pageSize: 100,
    dictType: 'countryside_message_type'
  }
  globalApi.getDictData(params).then((res) => {
    typeList.value = res.list
  })
}
/** 获取单人推送 */
const getpeopleList = () => {
  getMessageApi.getPeople().then((res) => {
    peopleList.value = res.map((item) => ({
      label: item.residentName,
      value: String(item.id)
    }))
  })
}
const filteredOptions = computed(() => {
  if (formData.form.pushMethod === '1') {
    return groupList.value
  } else if (formData.form.pushMethod === '2') {
    return peopleList.value
  }
  return []
})
const handleSendType = (e) => {
  formData.form.title = undefined
  formData.form.type = undefined
  formData.form.userId = undefined
  formData.form.content = undefined
  formData.form.pushMethod = '1'
  formData.form.templateCode = undefined
}

const handleRadio = (e) => {
  radioId.value = e
  formData.form.userId = ''
}
const handleUserId = (e) => {
  if (radioId.value == '1') {
    groupValue.value = e
    userIds.value = []
    getPeoplePage()
  } else {
    userIds.value = [parseInt(e)]
  }
}

const getPeoplePage = async () => {
  try {
    const res = await getMessageApi.getPeople()
    const filteredUserIds = []
    res.forEach((item) => {
      const labels = item.residentLabel.split(',')
      if (labels.includes(groupValue.value)) {
        if (!userIds.value.includes(item.id)) {
          filteredUserIds.push(item.id)
        }
      }
    })
    userIds.value = filteredUserIds
  } catch (error) {
    console.error('Error fetching people:', error)
  }
}
const handleType = (t) => {
  let content = 1
  typeList.value.forEach((t) => {
    if (t.label === formData.form.type) {
      content = t.value
    }
  })
  return Number(content)
}

/** 确定 */
const besurebtn = async () => {
  // 校验表单
  await formRef.value.validate()
  const data = {
    id: '',
    title: formData.form.title,
    type: handleType(formData.form.type),
    sendType: [parseInt(formData.form.sendType)],
    userId: userIds.value,
    content: formData.form.content,
    pushMethod: Number(formData.form.pushMethod),
    templateCode: formData.form.templateCode
  }
  getMessageApi.createMessage(data).then(() => {
    message.success('新增消息成功')
    emit('getAdd', props.editData.pageNo)
    visible.value = false
    formRef.value.resetFields()
  })
}
onMounted(() => {
  getpeopleList()
  getGroupPush()
  getPeoplePage()
  getmessageType()
  getSmsList()
  getSendType()
})
</script>
<style scoped>
.btnhover:hover {
  opacity: 0.8;
}
</style>
